package core.android.views.scrollview;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

/**
 * 仿淘宝商品详情页面上拉弹出下一个界面
 */
public class ToggleScrollView extends ScrollView {
    private int mScreenHeight;
    private LinearLayout wrapper;
    private PageOneScrollView pageOne;
    private PageTwoWebView pageTwo;
    private boolean ispageOne = true;

    final String mimeType = "text/html";
    final String encoding = "utf-8";


    public ToggleScrollView(Context context) {
        this(context, null);
    }

    public ToggleScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ToggleScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        initPages(attrs, defStyleAttr);
    }

    private void init() {
        setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
        //获得屏幕的宽度和计算设置的偏移量的像素值,并计算出menu的宽度
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        mScreenHeight = metrics.heightPixels;//得到屏幕的宽度(像素)
    }

    private void initPages(AttributeSet attrs, int defStyleAttr) {
        wrapper = new LinearLayout(getContext(), attrs, defStyleAttr);
        wrapper.setOrientation(LinearLayout.VERTICAL);
        addView(wrapper);

        pageOne = new PageOneScrollView(getContext(), attrs, defStyleAttr);
        pageTwo = new PageTwoWebView(getContext(), attrs, defStyleAttr);

        wrapper.addView(pageOne);
        wrapper.addView(pageTwo);

        pageOne.getLayoutParams().height = mScreenHeight;
        pageTwo.getLayoutParams().height = mScreenHeight;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            this.scrollTo(0, 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_UP:
                //隐藏在左边的距离
                int scrollY = getScrollY();
                int creteria = mScreenHeight / 5;//滑动多少距离
                if (ispageOne) {
                    if (scrollY <= creteria) {
                        //显示菜单
                        this.smoothScrollTo(0, 0);
                    } else {
                        //隐藏菜单
                        this.smoothScrollTo(0, mScreenHeight);
                        this.setFocusable(false);
                        ispageOne = false;
                    }
                } else {
                    int scrollpadding = mScreenHeight - scrollY;
                    if (scrollpadding >= creteria) {
                        this.smoothScrollTo(0, 0);
                        ispageOne = true;
                    } else {
                        this.smoothScrollTo(0, mScreenHeight);
                    }
                }
                return true;
        }
        return super.onTouchEvent(ev);
    }


    public void closeMenu() {
        if (ispageOne) return;
        this.smoothScrollTo(0, 0);
        ispageOne = true;
    }

    public void openMenu() {
        if (!ispageOne) return;
        this.smoothScrollTo(0, mScreenHeight);
        ispageOne = false;
    }

    /**
     * 切换页面
     */
    public void switchPage() {
        if (ispageOne) {
            openMenu();
        } else {
            closeMenu();
        }
    }

    public void addTabOne(View view) {
        if (pageOne != null) {
            pageOne.addView(view);
        }
    }

    public void pageTwoLoadUrl(String url) {
        if (pageTwo != null) {
            pageTwo.loadUrl(url);
        }
    }

    public void pageTwoLoadData(String data) {
        if (pageTwo != null) {
            pageTwo.loadDataWithBaseURL("about:blank", data, mimeType, encoding, "");
        }
    }

    /**
     * 释放资源
     */
    public void ondestory() {
        if (wrapper != null) {
            wrapper.removeAllViews();
        }
        if (pageTwo != null) {
            pageTwo.removeAllViews();
            pageTwo.destroy();
        }
    }

    private class PageOneScrollView extends ScrollView {
        private int mScreenHeight;
        public float oldY;
        private int t;

        public PageOneScrollView(Context context) {
            this(context, null);
        }

        public PageOneScrollView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public PageOneScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metrics);
            mScreenHeight = metrics.heightPixels;//得到屏幕的宽度(像素)
        }

        @Override
        public boolean onTouchEvent(MotionEvent ev) {

            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    //在滑动的时候获得当前值，并计算得到YS,用来判断是向上滑动还是向下滑动
                    float Y = ev.getY();
                    float Ys = Y - oldY;

                    //得到scrollview里面空间的高度
                    int childHeight = this.getChildAt(0).getMeasuredHeight();
                    //子控件高度减去scrollview向上滑动的距离
                    int padding = childHeight - t;
                    //Ys<0表示手指正在向上滑动，padding==mScreenHeight表示本scrollview已经滑动到了底部
                    if (Ys < 0 && padding == mScreenHeight) {
                        //让顶级的scrollview重新获得滑动事件
                        getParent().getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    break;
                case MotionEvent.ACTION_DOWN:
                    //手指按下的时候，获得滑动事件，也就是让顶级scrollview失去滑动事件
                    getParent().getParent().requestDisallowInterceptTouchEvent(true);
                    //并且记录Y点值
                    oldY = ev.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    getParent().getParent().requestDisallowInterceptTouchEvent(true);

                    break;


            }

            return super.onTouchEvent(ev);
        }

        @Override
        protected void onScrollChanged(int l, int t, int oldl, int oldt) {
            //t表示本scrollview向上滑动的距离
            this.t = t;
            super.onScrollChanged(l, t, oldl, oldt);
        }

    }

    private class PageTwoWebView extends WebView {
        public float oldY;
        private int t;

        public PageTwoWebView(Context context) {
            this(context, null);
        }

        public PageTwoWebView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public PageTwoWebView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }

        public void init() {
            if (Build.VERSION.SDK_INT >= 19) {
                getSettings().setLoadsImagesAutomatically(true);
            } else {
                getSettings().setLoadsImagesAutomatically(false);
            }
            getSettings().setJavaScriptEnabled(false);
        }

        @Override
        public boolean onTouchEvent(MotionEvent ev) {

            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:

                    float Y = ev.getY();
                    float Ys = Y - oldY;
                    //Ys>0表示正在向下滑动->t==0表示一定滑动到了顶部
                    if (Ys > 0 && t == 0) {
                        //然后让顶级那个scrolLview滑动滑动事件
                        getParent().getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    break;
                case MotionEvent.ACTION_DOWN:
                    //同样是获得滑动事件->记录位置
                    getParent().getParent().requestDisallowInterceptTouchEvent(true);
                    oldY = ev.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    getParent().getParent().requestDisallowInterceptTouchEvent(true);

                    break;
            }

            return super.onTouchEvent(ev);
        }

        @Override
        protected void onScrollChanged(int l, int t, int oldl, int oldt) {
            this.t = t;
            super.onScrollChanged(l, t, oldl, oldt);
        }

    }
}